<script lang="ts" setup>
import style from "./index.module.scss";
import { getImg } from "@/utils";
const duration = ref(200);
const searchParams = reactive({
  page: 1,
  page_size: 10,
});
const total = ref<number>(0);
const swiperRef = ref<any>(null);
const dataList = ref<any[]>([]);
const fetchDataList = async () => {
  const resData: any = await videoApi.queryList({
    page: searchParams.page,
    page_size: searchParams.page_size,
  });
  // console.log("列表数据:", resData);
  if (resData.status != "success") {
    showToast({
      message: resData.message,
      duration: 1500,
    });
    return;
  }
  // 在最后的位置加一条数据 实现无缝轮播
  total.value === 0 && (total.value = resData.data.count + 1);
  dataList.value =
    searchParams.page === 1
      ? [...resData.data.list]
      : [...dataList.value, ...resData.data.list];
};
onMounted(() => {
  dataList.value = [];
  fetchDataList();
});
const handleChange = (index: number) => {
  console.log("change", index, swiperRef.value);
  if (index % (searchParams.page_size - 1) === 0) {
    searchParams.page = searchParams.page + 1;
    fetchDataList();
  }
  if (dataList.value.length >= total.value) {
    dataList.value.length = 0;
    searchParams.page = 1;
    fetchDataList();
    const timer = setTimeout(() => {
      clearTimeout(timer);
      swiperRef.value.swipeTo(0, {
        immediate: true,
      });
    }, duration.value);
  }
  const playButton: any = document.querySelectorAll(".vjs-big-play-button")[
    index
  ];
  const playerList: any = document.querySelectorAll(".vjs-tech");
  playerList.forEach((el: any) => el.pause());
  const video = playerList[index];
  video && video.play();
  playButton && (playButton.style.display = "none");
};

const getTrackTop = () => {
  const swipeTrack: any = document.querySelector(".van-swipe__track");
  const rect = swipeTrack.getBoundingClientRect();
  return rect.top;
};
// @ts-ignore
const threshold = ref<number>(window.innerHeight / 2);
const startY = ref(0);
const endY = ref(0);
const handleDragStart = ({ index }: any) => {
  const start = getTrackTop();
  console.log("drag-start", index, start);
  startY.value = start;
};
const handleDragEnd = ({ index }: any) => {
  const end = getTrackTop();
  endY.value = end;
  console.log("drag-end", index, end);
  const distanceY = endY.value - startY.value;
  if (distanceY < 0) {
    console.log("鼠标向上滑");
    // 其它逻辑代码。。。
  }
  if (distanceY > 0) {
    console.log("鼠标向下滑");
    // 其它逻辑代码。。。
  }
};
const innerStyle = {
  width: "100%",
  height: "100vh",
};
function scrollToTop(index: number) {
  // console.log(index, swiperRef.value);
  swiperRef.value.next();
  // swiperRef.value.swipeTo(index, true);
  const playerList: any = document.querySelectorAll(".vjs-tech");
  const video = playerList[index + 1];
  video && video.play();
}
const handleEnded = (index: any) => {
  // console.log("播放完成", index);
  scrollToTop(index);
};

const handleClickPlayer = (event: any) => {
  // console.log(event);
  const target = event.target;
  if (!target.hasAttribute("data-vjs-player")) return;
  const video = target.querySelector(".vjs-tech");
  const playButton = target.querySelector(".vjs-big-play-button");
  if (video.paused) {
    video.play();
    playButton.style.display = "none";
  } else {
    video.pause();
    playButton.style.display = "block";
  }
};
const playerRef = ref(null);
const handlePlayerReady = (player: any) => {
  playerRef.value = player;
  player.on("canplaythrough", () => {
    // console.log("视频加载完成！");
  });
  player.on("error", () => {
    // console.log(`视频文件加载失败，请稍后重试！`);
  });
  player.on("stalled", () => {
    // console.log(`网络异常，请稍后重试！`);
  });
};
const isCollect = ref(false);
const handleCollect = debounce(() => {
  isCollect.value = !isCollect.value;
}, 200);
const videoJsOptions = {
  autoplay: false,
  controls: true,
  fluid: true,
  sources: [
    {
      src: getVideo("oceans.mp4"),
      type: "video/mp4",
    },
  ],
  poster: getImg("demo02.jpeg"),
  muted: false,
  controlBar: {
    currentTimeDisplay: true,
    timeDivider: true,
    durationDisplay: true,
    remainingTimeDisplay: false,
    children: [
      {
        name: "progressControl",
      },
      {
        name: "durationDisplay",
      },
    ],
  },
  userActions: {
    doubleClick: false,
  },
  responsive: false,
  webFullScreen: false,
};
</script>

<template>
  <van-swipe
    style="width: 100%; height: 100vh"
    :duration="duration"
    vertical
    :loop="false"
    :show-indicators="false"
    @change="handleChange"
    @drag-start="handleDragStart"
    @drag-end="handleDragEnd"
    ref="swiperRef"
  >
    <van-swipe-item
      v-for="(item, index) in dataList"
      :key="index"
      style="height: 100vh"
      :data-index="index"
      @click="(event) => handleClickPlayer(event)"
    >
      <div :class="style['video-index']">
        <div class="video-wrap">
          <div :style="innerStyle">
            <VideoJS
              @ended="() => handleEnded(index)"
              :options="{
                ...videoJsOptions,
                poster: item.cover,
                sources: [
                  {
                    src: item.video_url,
                    type: 'video/mp4',
                  },
                ],
              }"
              @ready="handlePlayerReady"
            />
          </div>
          <div class="introduce">
            <div class="userinfo">
              <div class="avatar">
                <img :src="getImg('demo01.jpeg')" alt="" />
              </div>
              <div class="txt">{{ item.title }}</div>
            </div>
            <!-- <EllipsisJS :content="item.content" /> -->
            <van-text-ellipsis
              rows="3"
              :content="item.content"
              expand-text="展开"
              collapse-text="收起"
            />
          </div>

          <div @click="handleCollect" class="collect">
            <img
              :src="getImg(isCollect ? 'like 1@2x.png' : 'like@2x(1).png')"
              alt=""
            />
          </div>
        </div>
      </div>
    </van-swipe-item>
  </van-swipe>
</template>
